/*
 * @lc app=leetcode.cn id=24 lang=cpp
 *
 * [24] 两两交换链表中的节点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;

        ListNode* dummy = new ListNode(-1);
        auto cur = dummy;
        while (head != nullptr && head->next != nullptr) {
            cur->next = head->next;

            ListNode* nNext = head->next->next;
            head->next->next = head;
            head->next = nNext;

            cur = head;
            head = head->next;
        }

        auto result = dummy->next;
        delete dummy;

        return result;
    }
};
// @lc code=end

